<template>
    <basic-container>
      <chc-datagrid :option="tableOption"
                 :data="list"
                 ref="crud"
                 :page="page"
                 v-model="form"
                 :table-loading="listLoading"
                 :before-open="handleOpenBefore"
                 @on-load="getList"
                 @search-change="handleFilter"
                 @refresh-change="handleRefreshChange"
                 @row-update="update"
                 @row-save="create">

        <template slot="isActive"
                  slot-scope="scope">
          {{scope.row.isActive?'是':'否'}}
        </template>

        <template slot="menuLeft">
          <el-button v-if="permissions['sys.role.add']"
                     class="filter-item"
                     @click="handleCreate"
                     size="small"
                     type="primary"
                     icon="el-icon-edit">添加
          </el-button>
        </template>
        <template slot="menu"
                  slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     v-if="permissions['sys.role.edit']"
                     @click="handleUpdate(scope.row,scope.index)">编辑
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-delete"
                     v-if="permissions['sys.role.delete']"
                     @click="handleDelete(scope.row,scope.index)">删除
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-plus"
                     plain
                     @click="handleMenuAuth(scope.row,scope.index)"
                     v-if="permissions['sys.role.menuAuth']">菜单权限
          </el-button>
        </template>
      </chc-datagrid>
    <el-dialog title="设置菜单权限" width="60%"
               :visible.sync="menuAuthDialogVisible">
      <auth-tree-table :show-header="false" ref="authTable" :height="400"  :data="menuAuthData" :columns="menuAuthColumns" row-key="id"></auth-tree-table>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="updateMenuAuth(roleId)">更 新
        </el-button>
      </div>
    </el-dialog>
    </basic-container>
</template>

<script>
  import { getObj,addObj,putObj, delObj, fetchList,fetchMenuAuthTree,saveMenuAuth} from '@/modules/sys/api/role'
  import {tableOption} from './role'
  import {mapGetters} from 'vuex'
  import authTreeTable from '@/components/auth-tree-table';

  export default {
    name: 'table_role',
    components: {authTreeTable },
    data() {
      return {
        tableOption: tableOption,
        //菜单权限
        menuAuthData: [],
        menuAuthDialogVisible: false,
        menuAuthColumns:[
            {
              label: '菜单',
              prop: 'label',
              width: 200
            },
            {
              label: '权限',
              prop: 'options',
            }
          ],

        // dsScopeData: [],
        // checkedDsScope: [],
        // defaultProps: {
        //   label: "label",
        //   value: 'id'
        // },
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        list: [],
        listLoading: false,
        form: {
          id: undefined,
          name: undefined,
          remark: undefined,
          orgId: undefined,
          isActive : undefined
        },
        roleId: undefined

      }
    },
    created() {
    },
    computed: {
      ...mapGetters(['elements', 'permissions','userInfo'])
    },
    methods: {
      getList(page, params) {
        this.listLoading = true
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params)).then(response => {
          this.list = response.data.data.records
          this.page.total = response.data.data.total
          this.listLoading = false
        })
      },
      handleRefreshChange() {
        this.getList(this.page)
      },
      handleFilter(param) {
        this.page.page = 1;
        this.getList(this.page, param);
      },
      handleCreate() {
        this.$refs.crud.rowAdd();
        this.resetForm();
      },
      handleOpenBefore(show, type) {
        // fetchTree().then(response => {
        //   this.dsScopeData = response.data.data;
        //   if (this.form.dsScope) {
        //     this.checkedDsScope = (this.form.dsScope).split(",")
        //   } else {
        //     this.checkedDsScope = []
        //   }
        // });
        show();
      },
      handleUpdate(row, index) {
        this.$refs.crud.rowEdit(row, index);
      },
      handleMenuAuth(row) {
        fetchMenuAuthTree(row.id)
          .then(response => {
            this.menuAuthData = response.data.data.children
            // // 解析出所有的太监节点
            // this.checkedKeys = this.resolveAllEunuchNodeId(this.treeData, this.checkedKeysData.data, [])
            this.menuAuthDialogVisible = true
            this.roleId = row.id
          })
      },
      // handleOrgPermission(row) {
      //   fetchRoleOrg(row.id)
      //     .then(response => {
      //       this.orgCheckedKeysData = response.data
      //       return fetchOrgTree()
      //     })
      //     .then(response => {
      //       this.orgTreeData = response.data.data
      //       // 解析出所有的太监节点
      //       this.orgCheckedKeys = this.resolveAllEunuchNodeId(this.orgTreeData, this.orgCheckedKeysData.data, [])
      //       this.dialogStatus = 'orgPermission'
      //       this.orgDialogPermissionVisible = true
      //       this.roleId = row.id
      //     })
      // },
      /**
       * 解析出所有的太监节点id
       * @param json 待解析的json串
       * @param idArr 原始节点数组
       * @param temp 临时存放节点id的数组
       * @return 太监节点id数组
       */
      // resolveAllEunuchNodeId(json, idArr, temp) {
      //   for (let i = 0; i < json.length; i++) {
      //     const item = json[i]
      //     // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
      //     if (item.children && item.children.length !== 0) {
      //       this.resolveAllEunuchNodeId(item.children, idArr, temp)
      //     } else {
      //       let idArr1 =idArr.filter(id => id == item.id);
      //       if (idArr1.length>0)
      //         temp.push(idArr1[0]);
      //     }
      //   }
      //   return temp
      // },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      getNodeData(data, done) {
        done();
      },
      handleDelete(row, index) {
        var _this = this
        this.$confirm('是否确认删除名称为"' + row.name + '"'+ '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(row.id)
        }).then(() => {
          this.getList(this.page)
          this.list.splice(index, 1);
          _this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        }).catch(function () {
        })
      },
      create(row, done, loading) {
        if (this.form.dsType === 1){
          this.form.dsScope = this.$refs.scopeTree.getCheckedKeys().join(',')
        }
        addObj(this.form).then(() => {
          this.getList(this.page)
          done();
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
        }).catch(() => {
          loading();
        });
      },
      update(row, index, done, loading) {
        if (this.form.dsType === 1){
          this.form.dsScope = this.$refs.scopeTree.getCheckedKeys().join(',')
        }
        putObj(this.form).then(() => {
          this.getList(this.page)
          done();
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        }).catch(() => {
          loading();
        });
      },
      updateMenuAuth(roleId) {
        let data=[];
        let visit = function(row){
          let row1 = {id: row.id,options:row.options};
          data.push(row1);
          if (row.children){
            row.children.forEach(visit)
          }
        }
        this.menuAuthData.forEach(visit);
        saveMenuAuth(roleId,data)
          .then(response => {
            this.$notify({
                title: "成功",
                message: "设置权限成功",
                type: "success",
                duration: 2000
              })
            this.menuAuthDialogVisible = false
            })
          .catch(() => {
            this.$notify({
              title: "失败",
              message: "设置权限失败",
              type: "error",
              duration: 2000
            })
          })

        // this.menuIds = ''
        // this.menuIds = this.$refs.menuTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.menuTree.getHalfCheckedKeys().join(','))
        // permissionUpd(roleId, this.menuIds).then(() => {
        //   this.dialogPermissionVisible = false
        //       this.$notify({
        //         title: '成功',
        //         message: '修改成功',
        //         type: 'success',
        //         duration: 2000
        //       })
        //   // fetchMenuTree()
        //   //   .then(response => {
        //   //     this.form = response.data.data
        //   //     //return fetchRoleMenuTree(roleId)
        //   //   })
        //     // .then(response => {
        //     //   //this.checkedKeys = response.data
        //     //   this.$notify({
        //     //     title: '成功',
        //     //     message: '修改成功',
        //     //     type: 'success',
        //     //     duration: 2000
        //     //   })
        //     // })
        // })
      },
      // updateOrgPermession(roleId) {
      //   this.orgIds = ''
      //   this.orgIds = this.$refs.orgTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.orgTree.getHalfCheckedKeys().join(','))
      //   orgPermissionUpd(roleId, this.orgIds).then(() => {
      //     this.orgDialogPermissionVisible = false
      //         this.$notify({
      //           title: '成功',
      //           message: '修改成功',
      //           type: 'success',
      //           duration: 2000
      //         })
      //     // fetchOrgree()
      //     //   .then(response => {
      //     //     this.form = response.data.data
      //     //     //return fetchRoleMenuTree(roleId)
      //     //   })
      //       // .then(response => {
      //       //   //this.checkedKeys = response.data
      //       //   this.$notify({
      //       //     title: '成功',
      //       //     message: '修改成功',
      //       //     type: 'success',
      //       //     duration: 2000
      //       //   })
      //       // })
      //   })
      // },
      resetForm() {
        this.form = {
          isActive: true,
          orgId: this.userInfo.orgId
        }
      }


    }
  }
</script>
<style lang="scss">
</style>
